﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using Ext.Net.MVC;
using Ext.Net;
using SDSystem.Models;

namespace SDSystem.Controllers
{
    public class NewsController : Controller
    {
        //
        // GET: /News/

        #region News

        private ForumEntities db = new ForumEntities();

        public ActionResult Index()
        {
            return View();
        }

        //Search News
        public ActionResult Search()
        {
            var store = X.GetCmp<Store>("NewsDataStore");
            Session["sNewsTitle"] = X.GetCmp<TextField>("txtNewsTitle").Text;
            Session["sNewsDescription"] = X.GetCmp<TextField>("txtNewsDescription").Text;
            Session["sGroupNewsName"] = X.GetCmp<TextField>("txtGroupNewsName").Text;
            store.Reload();
            return this.Direct();
        }

        public ActionResult ClearSearch()
        {
            var store = X.GetCmp<Store>("NewsDataStore");
            // Clear search here
            Session["sNewsTitle"] = X.GetCmp<TextField>("txtNewsTitle").Text="";
            Session["sNewsDescription"] = X.GetCmp<TextField>("txtNewsDescription").Text="";
            Session["sGroupNewsName"] = X.GetCmp<TextField>("txtGroupNewsName").Text="";
            store.Reload();
            return this.Direct();
        }

        //Create News
        public ActionResult Create()
        {
            var query = db.GroupNews.Select(c => new { c.GroupNewsId, c.GroupName });
            ViewBag.ListGroupNews = new SelectList(query.AsEnumerable(), "GroupNewsId", "GroupName");
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(News nw)
        {
            if(ModelState.IsValid)
            {
                string group = Request.Form["ListGroupNews"];
                nw.GroupNews = Convert.ToInt32(group);
                nw.DateCreate = DateTime.Now;
                nw.Views = 0;
                nw.IsActive = true;
                db.News.AddObject(nw);
                db.SaveChanges();
                X.Msg.Notify("Successfull", "Create News success").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Failed!!!", "Create News non success").Show();
            return this.FormPanel();
        }

        //Edit News
        public ActionResult Edit(int id)
        {
            News nw = db.News.SingleOrDefault(e => e.NewsId == id);
            var query = db.GroupNews.Select(c => new { c.GroupNewsId, c.GroupName });
            ViewBag.ListGroupNews = new SelectList(query.AsEnumerable(), "GroupNewsId", "GroupName");
            return View(nw);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(News nw)
        {
            News nw1 = db.News.SingleOrDefault(e => e.NewsId == nw.NewsId);
            if(ModelState.IsValid)
            {
                db.News.Detach(nw1);
                db.News.Attach(nw);
                db.ObjectStateManager.ChangeObjectState(nw, EntityState.Modified);
                db.SaveChanges();
                X.Msg.Notify("Successfull", "Create News success").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Failed!!!", "Create News non success").Show();
            return this.FormPanel();
        }

        //News Data
        public ActionResult NewsData(StoreRequestParameters parameters)
        {
            string newstitle=(String)Session["sNewsTitle"];
            string newsdescription=(String)Session["sNewsDescription"];
            string groupnewsname=(String)Session["sGroupNewsName"];
            var result = (from newsDB in db.News
                          join gnewsDB in db.GroupNews on newsDB.GroupNews equals gnewsDB.GroupNewsId
                          select new
                                     {
                                         newsDB.NewsId,
                                         newsDB.Title,
                                         newsDB.Description,
                                         newsDB.DateCreate,
                                         gnewsDB.GroupName,
                                         newsDB.Views,
                                         newsDB.IsActive
                                     })
                                    .Where(e=>(string.IsNullOrEmpty(newstitle)||e.Title.Contains(newstitle)) &&
                                                (string.IsNullOrEmpty(newsdescription) || e.Title.Contains(newsdescription)) &&
                                                (string.IsNullOrEmpty(groupnewsname) || e.Title.Contains(groupnewsname)));
            // Sorting
            if (!string.IsNullOrEmpty(parameters.SimpleSort))
            {
                result =
                    result.OrderBy(parameters.SimpleSort +
                                   (parameters.SimpleSortDirection == SortDirection.DESC ? " desc" : " asc"));
            }
            else
            {
                result = result.OrderBy(ent => ent.NewsId);
            }

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count())
            {
                limit = result.Count() - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.Skip(parameters.Start).Take(limit);
            return this.Store(rangeData, result.Count());
        }

        #endregion

        #region GroupNews

        public ActionResult ListGroupNews()
        {
            return View();
        }

        //Create GroupNews
        public ActionResult CreateGroupNews()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateGroupNews(GroupNew gn)
        {
            if (ModelState.IsValid)
            {
                var httpPostedFileBase = Request.Files[0];
                if (httpPostedFileBase != null)
                {
                    httpPostedFileBase.SaveAs(Server.MapPath("~/") + "//Content//Upload//" + httpPostedFileBase.FileName);
                    gn.Image = "/Content/Upload/" + httpPostedFileBase.FileName;
                }
                gn.IsActive = true;
                db.GroupNews.AddObject(gn);
                db.SaveChanges();
                X.Msg.Notify("Successfull", "GroupNews is saved").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Failed", "No Groupnews is created");
            return this.FormPanel();
        }

        //Edit GroupNews
        public ActionResult EditGroupNews(int id)
        {
            GroupNew gn = db.GroupNews.SingleOrDefault(e => e.GroupNewsId == id);
            Session["sGroupNewsImage"]=ViewBag.GroupNewsImage = gn.Image;
            return View(gn);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditGroupNews(GroupNew gn)
        {
            GroupNew gn1 = db.GroupNews.SingleOrDefault(e => e.GroupNewsId == gn.GroupNewsId);
            if(ModelState.IsValid)
            {
                var httpPostedFileBase = Request.Files[0];
                if (httpPostedFileBase != null && httpPostedFileBase.FileName!="")
                {
                    httpPostedFileBase.SaveAs(Server.MapPath("~/") + "//Content//Upload//" + httpPostedFileBase.FileName);
                    gn.Image = "/Content/Upload/" + httpPostedFileBase.FileName;
                }
                else
                {
                    gn.Image = Convert.ToString(Session["sGroupNewsImage"]);
                }
                db.GroupNews.Detach(gn1);
                db.GroupNews.Attach(gn);
                db.ObjectStateManager.ChangeObjectState(gn, EntityState.Modified);
                db.SaveChanges();
                X.Msg.Notify("Successfull", "Groupnews is saved").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Failed", "No GroupNews is saved");
            return this.FormPanel();
        }
        //GroupNews Data
        public ActionResult GroupNewsData(StoreRequestParameters parameters)
        {
            var result = from gnews in db.GroupNews
                         select new
                                    {
                                        gnews.GroupNewsId,
                                        gnews.GroupName,
                                        gnews.Image,
                                        gnews.Description,
                                        gnews.IsActive
                                    };
            // Sorting
            if (!string.IsNullOrEmpty(parameters.SimpleSort))
            {
                result =
                    result.OrderBy(parameters.SimpleSort +
                                   (parameters.SimpleSortDirection == SortDirection.DESC ? " desc" : " asc"));
            }
            else
            {
                result = result.OrderBy(ent => ent.GroupNewsId);
            }

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count())
            {
                limit = result.Count() - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.Skip(parameters.Start).Take(limit);
            return this.Store(rangeData, result.Count());
        }

        #endregion

    }
}
